const {model: userModel} = require("../models/user");
const {model: menuModel} = require("../models/menu");

/**
 * 查询用户是否存在 true存在 false不存在
 * @param params    传参 userId->id
 * @returns {Promise<boolean>}  结果
 */
function includeUserById(params) {
    return new Promise(async (resolve, reject) => {
        userModel.findOne({id: params.userId}, (err, docs) => {
            resolve(!!docs)
        })
    })
}

/**
 * 查询菜单是否存在 true存在 false不存在
 * @param params    传参 userId menuId
 * @returns {Promise<boolean>}  结果
 */
function includeMenuByMenuId(params) {
    return new Promise(async (resolve, reject) => {
        menuModel.findOne({userId: params.userId, menuId: params.menuId}, (err, docs) => {
            resolve(!!docs ? docs.menuId : '')
        })
    })
}

/**
 * 用户内记录评论的文章
 * @param params 传参 articleId userId
 * @returns {Promise<object>} 结果
 */
function setUserViewArticles(params) {
    return new Promise((resolve, reject) => {
        const filter = {id: params.userId}
        const updateData = {
            $push: {
                viewArticles: {
                    articleId: params.articleId,
                    craeteTime: Date.now()
                }
            }
        }
        userModel.findOneAndUpdate(filter, updateData, (err, docs) => {
            if (!err) {
                resolve({code: 1, data: null, msg: '记录阅读的文章成功'})
            } else {
                reject({code: 0, data: null, msg: err.message})
            }
        })
    })
}

/**
 * 阅读量
 * @param model 模型
 * @param params 传参 articleId
 * @returns {Promise<object>} 结果
 */
function setArticleViewCount(model, params) {
    return new Promise((resolve, reject) => {
        model.findOneAndUpdate({articleId: params.articleId}, {$inc: {viewCount: 1}}, (err, docs) => {
            if (!err) {
                resolve({code: 1, data: null, msg: '记录阅读的文章成功'})
            } else {
                reject({code: 0, data: null, msg: err.message})
            }
        })
    })
}

/**
 * 获取最大置顶文章ID
 * @param model 模型
 * @param params 传参 userId
 * @returns {Promise<object>} 结果
 */
function getMaxTopByUserId(model, params){
    return new Promise((resolve, reject) => {
        model.findOne({userId: params.userId}).sort({top: -1}).exec((err, docs) => {
            if(!err){
                resolve({code: 1, data: docs, msg: '获取最大置顶成功'})
            }else{
                reject({code: 0, data: null, msg: err.message})
            }
        })
    })
}

module.exports = {includeUserById, includeMenuByMenuId, setUserViewArticles, setArticleViewCount, getMaxTopByUserId}
